﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Ivi.Visa;
using NationalInstruments.Visa;
using IniFiles;
using Instruments;

namespace Cali
{
    public partial class Form_Ins : Form
    {
        private bool bEdited;
        public TextBox tbIndex;
        public IniConfig Ininfo;
        private TreeNode ndGpib;
        private TreeNode ndTcpip;
        private TreeNode ndUSB;
        private string m_sIniFilePath;
        private IniFile m_iniFile;
        private System.Collections.Specialized.NameValueCollection m_InsInfo;

        public static List<string> lsLoadType;
        private List<string> lsLoadName;
        private List<string> lsLoadNick;
        private List<string> lsChannelAdd;
        private List<string> lsChannelType;

        protected DataTable dt1, dt2;

        public Form_Ins()
        {
            InitializeComponent();
            lsLoadNick = new List<string>() {"电子负载1", "电子负载2", "电子负载3", "电子负载4" };
            lsChannelAdd = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8" };
            //lsLoadType = new List<string>() { "6314", "63203", "63205", "63210", "IT87" };
            lsChannelType = new List<string>();// { "63102", "63103", "63106", "63107", "63112A"};

            tbIndex = txb_Source1;
            ndGpib = new TreeNode("GPIB");
            ndTcpip = new TreeNode("TCP/IP");
            ndUSB = new TreeNode("USB");
            m_sIniFilePath = System.IO.Path.Combine(Application.StartupPath, "Ins.ini");
            m_iniFile = new IniFile(m_sIniFilePath);
            m_InsInfo = new System.Collections.Specialized.NameValueCollection();
            m_iniFile.ReadSectionValues("Instruments", m_InsInfo);

            Ininfo = Form_Main.m_Ininfo;
        }

        protected override void Dispose(bool disposing)
        {
            if(disposing)
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void AddToResourceTree()
        {
            if (ndGpib.Nodes.Count != 0)
                InsTreeView.Nodes.Add(ndGpib);
            if (ndTcpip.Nodes.Count != 0)
                InsTreeView.Nodes.Add(ndTcpip);
            if (ndUSB.Nodes.Count != 0)
                InsTreeView.Nodes.Add(ndUSB);
        }

        private void AddToResourceNode(string resourceName, HardwareInterfaceType intType)
        {
            int nIndex = GetCollectionIndex(resourceName);
            TreeNode node = new TreeNode(resourceName);

            node.ToolTipText = resourceName;
            if (nIndex > -1)
                node.Text = m_InsInfo[nIndex];
            else
                m_InsInfo.Add(resourceName, resourceName);
            
            switch(intType)
            {
                case HardwareInterfaceType.Gpib:
                    ndGpib.Nodes.Add(node);
                    break;
                case HardwareInterfaceType.Tcp:
                    ndTcpip.Nodes.Add(node);
                    break;
                case HardwareInterfaceType.Usb:
                    ndUSB.Nodes.Add(node);
                    break;
                default:
                    break;
            }
        }

        private void FindResources()
        {
            using(var rm = new ResourceManager())
            {
                try
                {
                    IEnumerable<string> resources = rm.Find("?*");
                    foreach(string s in resources)
                    {
                        ParseResult parseResult = rm.Parse(s);
                        AddToResourceNode(s, parseResult.InterfaceType);
                    }
                    AddToResourceTree();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void cleanResourceNodes()
        {
            ndGpib.Nodes.Clear();
            ndTcpip.Nodes.Clear();
            ndUSB.Nodes.Clear();
        }

        private int GetCollectionIndex(string key)
        {
            for (int i = 0; i < m_InsInfo.Count; i++)
            {
                if (key == m_InsInfo.AllKeys[i])
                    return i;
            }
            return -1;
        }

        private void GetChildNodeInfo(TreeNode node0)
        {
            TreeNode node = node0.FirstNode;
            if (node != null)
            {
                if (GetCollectionIndex(node.ToolTipText) > -1)
                    m_InsInfo.Set(node.ToolTipText, node.Text);
                else
                    m_InsInfo.Add(node.ToolTipText, node.Text);
            }
            while(node != node0.LastNode)
            {
                node = node.NextNode;
                if (GetCollectionIndex(node.ToolTipText) > -1)
                    m_InsInfo.Set(node.ToolTipText, node.Text);
                else
                    m_InsInfo.Add(node.ToolTipText, node.Text);
            }
        }

        private void SaveInsInfo()
        {
            GetChildNodeInfo(ndGpib);
            GetChildNodeInfo(ndTcpip);
            GetChildNodeInfo(ndUSB);
            m_iniFile.EraseSection("Instruments");
            int nCount = m_InsInfo.Count;
            string key, value;
            for (int i = 0; i < m_InsInfo.Count; i++)
            {
                key = m_InsInfo.AllKeys[i];
                value = m_InsInfo[i];
                m_iniFile.WriteString("Instruments", m_InsInfo.AllKeys[i], m_InsInfo[i]);
            }
        }

        private void Ins_Load(object sender, EventArgs e)
        {
            bEdited = false;
            InsTreeView.Nodes.Clear();
            cleanResourceNodes();
            FindResources();
            InsTreeView.ExpandAll();

            lsLoadName = Ininfo._sOutput.ToList();

            if(cbb_PSUs.Items.Count.Equals(0))
            {
                cbb_PSUs.Items.Add("PSU1");
                cbb_PSUs.Items.Add("PSU2");
            }
            cbb_PSUs.SelectedIndex = 0;

            for (int i = 0; i < 8; i++)
            {
                cbb_LoadNumber.Items.Add((i + 1).ToString());
                cbb_VLoadNumber.Items.Add((i + 1).ToString());
            }

            cbb_LoadNumber.Text = Ininfo._nLoad_No.ToString();
            cbb_VLoadNumber.Text = Ininfo._nVLoad_No.ToString();
            txb_Source1.Text = Ininfo._sSources[0];
            txb_Source2.Text = Ininfo._sSources[1];
            txb_PM1.Text = Ininfo._sPowerMeters[0];
            txb_PM2.Text = Ininfo._sPowerMeters[1];
            txb_EL1.Text = Ininfo._sELoads[0];
            txb_EL2.Text = Ininfo._sELoads[1];
            txb_EL3.Text = Ininfo._sELoads[2];
            txb_EL4.Text = Ininfo._sELoads[3];

            dt1 = new DataTable("PSU1");
            dt1.Columns.Add("Load Name", System.Type.GetType("System.String"));
            dt1.Columns.Add("Load Type", System.Type.GetType("System.String"));
            dt1.Columns.Add("Load Index", System.Type.GetType("System.String"));
            dt1.Columns.Add("Chan Type", System.Type.GetType("System.String"));
            dt1.Columns.Add("Chan Index", System.Type.GetType("System.String"));

            int nEloadIndex;
            for (int i = 0; i < int.Parse(cbb_LoadNumber.Text); i++)
            {
                dt1.Rows.Add();
                nEloadIndex = int.Parse(Ininfo._sLoad_Indexs[i].Trim());
                dt1.Rows[i][0] = Ininfo._sOutput[i].Trim();
                if(int.Parse(Ininfo._sLoad_Type[i]) < lsLoadType.Count)
                    dt1.Rows[i][1] = lsLoadType.ElementAt(nEloadIndex);
                dt1.Rows[i][2] = lsLoadNick.ElementAt(nEloadIndex); //需要验证修补

                if (Calibration.ELoads[nEloadIndex] != null)
                {
                    Calibration.ELoads[nEloadIndex].Init();
                    lsChannelType = Calibration.ELoads[nEloadIndex]._lsChanType;
                }
                if(int.Parse(Ininfo._sLoad_Chan[i].Trim())-1 < lsChannelType.Count)
                    dt1.Rows[i][3] = lsChannelType.ElementAt(int.Parse(Ininfo._sLoad_Chan[i].Trim())-1);
                dt1.Rows[i][4] = Ininfo._sLoad_Chan[i].Trim();
            }

            dgvLoadSet.DataSource = dt1;
            for (int i = 1; i < 5; i++)
            {
                dgvLoadSet.Columns[i].Width = 100;
                //dgvLoadSet.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
                //dgvLoadSet.ColumnHeadersHeight = dgvLoadSet.RowTemplate.Height;
                dgvLoadSet.Columns[i].HeaderCell.Style.BackColor = Color.Brown;
                dgvLoadSet.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
        }

        private void InsTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string str = e.Node.ToolTipText;
            Visa ins;
            tbIndex.Text = e.Node.ToolTipText;
            if(GetCollectionIndex(str) > -1)
            {
                ins = new Visa(str);
                lbl_Des.Text = ins._szDesc;
            }
            if (lbl_Des.Text.Contains("句柄创建失败"))
                tbIndex.Text = string.Empty;
        }
        private void txb_Source1_Click(object sender, EventArgs e)
        {
            tbIndex = txb_Source1;
        }

        private void txb_Source2_Click(object sender, EventArgs e)
        {
            tbIndex = txb_Source2;
        }

        private void txb_PM1_Click(object sender, EventArgs e)
        {
            tbIndex = txb_PM1;
        }

        private void txb_PM2_Click(object sender, EventArgs e)
        {
            tbIndex = txb_PM2;
        }
        private void textBox_EL1_Click(object sender, EventArgs e)
        {
            tbIndex = txb_EL1;
        }

        private void textBox_EL2_Click(object sender, EventArgs e)
        {
            tbIndex = txb_EL2;
        }

        private void textBox_EL3_Click(object sender, EventArgs e)
        {
            tbIndex = txb_EL3;
        }

        private void textBox_EL4_Click(object sender, EventArgs e)
        {
            tbIndex = txb_EL4;
        }

        private void dgvLoadSet_CurrentCellChanged(object sender, EventArgs e)
        {
            SaveInsID();

            if (dgvLoadSet.CurrentCell != null)
            {
                int colIndex = dgvLoadSet.CurrentCell.ColumnIndex;
                int rowIndex = dgvLoadSet.CurrentCell.RowIndex;
                int nEloadIndex;
                DataGridViewColumn column = dgvLoadSet.CurrentCell.OwningColumn;
                switch (column.Name)
                {
                    case "Load Name":
                        comboBox1.DataSource = lsLoadName;
                        break;
                    case "Load Type":
                        comboBox1.DataSource = lsLoadType;
                        break;
                    case "Load Index":
                        comboBox1.DataSource = lsLoadNick;
                        break;
                    case "Chan Type":
                        if (dgvLoadSet.Rows[rowIndex].Cells[1].Value.ToString().Length > 2)  //Load Type不为空
                        {
                            nEloadIndex = lsLoadNick.IndexOf(dgvLoadSet.Rows[rowIndex].Cells[2].Value.ToString());
                            ELoad eLoad = new ELoad(Ininfo._sELoads[nEloadIndex]);
                            eLoad.Init();
                            lsChannelType = eLoad._lsChanType;
                        }
                        comboBox1.DataSource = lsChannelType;
                        break;
                    case "Chan Index":
                        comboBox1.DataSource = lsChannelAdd;
                        break;
                    default:
                        break;
                }

                Point p = dgvLoadSet.Location;
                Rectangle rect = dgvLoadSet.GetCellDisplayRectangle(colIndex, rowIndex, false);
                comboBox1.Left = rect.Left + p.X;
                comboBox1.Top = rect.Top + p.Y;
                comboBox1.Width = rect.Width;
                comboBox1.Height = rect.Height;
                //将单元格的内容显示为下拉列表的当前项
                if (dgvLoadSet.Rows[rowIndex].Cells[colIndex].Value != null)
                {
                    string consultingRoom = dgvLoadSet.Rows[rowIndex].Cells[colIndex].Value.ToString();
                    int index = comboBox1.Items.IndexOf(consultingRoom);
                    if (colIndex == 3)
                    {
                        string str = dgvLoadSet.Rows[rowIndex].Cells[4].Value.ToString();
                        if (str.Length > 0)
                            index = int.Parse(str.Trim()) - 1;
                    }
                    comboBox1.SelectedIndex = index;
                }
                //如果是要显示下拉列表的列的话
                comboBox1.Visible = true;
            }
        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ELoad eLoad;
            int Index = comboBox1.SelectedIndex;
            int nEloadIndex;
            int rowIndex = dgvLoadSet.CurrentCell.RowIndex;
            int colIndex = dgvLoadSet.CurrentCell.ColumnIndex;

            bEdited = true;
            if (colIndex == 1)    //LoadType
            {
                if (Ininfo._sELoads[Index] != string.Empty)
                {
                    try
                    {
                        if (Calibration.ELoads[Index] != null)
                            eLoad = Calibration.ELoads[Index];
                        else
                            eLoad = new ELoad(Ininfo._sELoads[Index]);

                        if (eLoad._szDesc.Contains(lsLoadType[Index]))
                        {
                            dgvLoadSet.Rows[rowIndex].Cells[1].Value = lsLoadType[Index];
                            dgvLoadSet.Rows[rowIndex].Cells[2].Value = lsLoadNick[Index];
                        }
                        else
                        {
                            dgvLoadSet.Rows[rowIndex].Cells[1].Value = string.Empty;
                            dgvLoadSet.Rows[rowIndex].Cells[2].Value = string.Empty;
                        }
                        Ininfo._sLoad_Indexs[Index] = Index.ToString(); //目的：存储ELoadIdex
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }
            }
            else if (colIndex == 2)    //Load Nike
            {
                if (Index < lsLoadType.Count)
                    dgvLoadSet.Rows[rowIndex].Cells[1].Value = lsLoadType[Index];
                else
                    dgvLoadSet.Rows[rowIndex].Cells[1].Value = string.Empty;
            }
            else if (colIndex == 3)
            {
                dgvLoadSet.Rows[rowIndex].Cells[4].Value = lsChannelAdd[Index];
            }
            else if(colIndex == 4)
            {
                if (dgvLoadSet.Rows[rowIndex].Cells[1].Value.ToString().Length > 2)  //Load Type不为空
                {
                    nEloadIndex = lsLoadNick.IndexOf(dgvLoadSet.Rows[rowIndex].Cells[2].Value.ToString());
                    try
                    {
                        eLoad = new ELoad(Ininfo._sELoads[nEloadIndex]);
                        eLoad.Init();
                        lsChannelType = eLoad._lsChanType;
                    }
                    catch (Exception)
                    {
                    }
                }
                if (Index < lsChannelType.Count)
                    dgvLoadSet.Rows[rowIndex].Cells[3].Value = lsChannelType[Index];
                else
                    dgvLoadSet.Rows[rowIndex].Cells[3].Value = string.Empty;
            }
        }

        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dgvLoadSet.CurrentCell != null && comboBox1.SelectedIndex > -1 && comboBox1.SelectedIndex < comboBox1.Items.Count)
                dgvLoadSet.CurrentCell.Value = comboBox1.Items[comboBox1.SelectedIndex];
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bEdited = false;
            for (int i = 0; i < Ininfo._nLoad_No; i++)
            {
                Ininfo._sLoad_Indexs[i] = lsLoadNick.IndexOf(dt1.Rows[i][2].ToString()).ToString();
                Ininfo._sLoad_Chan[i] = dt1.Rows[i][4].ToString();
            }
            SaveInsID();
            Ininfo.SaveGeneralConfig();
        }

        private void SaveInsID()
        {
            Ininfo._sELoads[0] = txb_EL1.Text;
            Ininfo._sELoads[1] = txb_EL2.Text;
            Ininfo._sELoads[2] = txb_EL3.Text;
            Ininfo._sELoads[3] = txb_EL4.Text;

            Ininfo._sSources[0] = txb_Source1.Text;
            Ininfo._sSources[1] = txb_Source2.Text;

            Ininfo._sPowerMeters[0] = txb_PM1.Text;
            Ininfo._sPowerMeters[1] = txb_PM2.Text;
        }
        private void cbb_LoadNumber_SelectionChangeCommitted(object sender, EventArgs e)
        {
            bEdited = true;
            int nLoadNum = cbb_LoadNumber.SelectedIndex + 1;
            int n = dgvLoadSet.Rows.Count - nLoadNum;
            while(n != 0)
            {
                if (n > 0)
                {
                    dt1.Rows.RemoveAt(dt1.Rows.Count - 1);
                }
                else
                {
                    dt1.Rows.Add();
                }
                
                n = dgvLoadSet.Rows.Count - nLoadNum;
            }
            //dgvLoadSet.DataSource = null;
            //dgvLoadSet.DataSource = dt1;
        }

        private void cbb_PSUs_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if(Ininfo._bDual)
            {
                if (cbb_PSUs.SelectedIndex.Equals(0))
                    dgvLoadSet.DataSource = dt1;
                else
                    dgvLoadSet.DataSource = dt2;
            }
            else
            {
                cbb_PSUs.SelectedIndex = 0;
            }
        }

        private void Ins_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (bEdited)
                if (MessageBox.Show("是否保存？", "提示：", MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes))
                {
                    this.btnSave_Click(sender, e);
                }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            bEdited = false;
            this.Close();
        }

        private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (dgvLoadSet.CurrentCell.OwningColumn.Name.Equals("Column1"))
            {
                if (e.KeyCode.Equals(Keys.Enter))
                {
                    if (!Ininfo._sOutput.Contains(comboBox1.Text))
                    {
                        dgvLoadSet.CurrentCell.Value = comboBox1.Text;
                        lsLoadName.Add(comboBox1.Text);
                    }
                }
            }
        }
    }
}
